<template>
  <div class="history-panel">
    <el-card class="history-card">
      <template #header>
        <div class="panel-header">
          <h3>历史记录</h3>
        </div>
      </template>
      <div class="recent-generations">
        <el-scrollbar 
          height="calc(100vh - 200px)" 
          ref="scrollbarRef"
          @scroll="handleScroll"
        >
          <el-empty 
            v-if="historyTasks.length === 0 && !loading" 
            description="暂无生成记录">
          </el-empty>
          <div v-else class="history-grid">
            <div 
              v-for="task in historyTasks" 
              :key="task.taskId" 
              class="history-item"
              @click="handleHistoryItemClick(task)"
            >
              <div class="history-image-container">
                <el-image 
                  v-if="task.status === 'COMPLETED' && taskImageUrls.get(task.taskId)"
                  :src="taskImageUrls.get(task.taskId)" 
                  fit="cover"
                  class="history-image"
                  :preview-src-list="[taskImageUrls.get(task.taskId)]"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><warning /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div v-else class="task-status">
                  <el-tag :type="getTaskStatusType(task.status)">
                    {{ getTaskStatusText(task.status) }}
                  </el-tag>
                </div>
              </div>
              <div class="history-info">
                <span class="history-date">{{ formatDateFromString(task.createdAt) }}</span>
                <el-tooltip 
                  v-if="task.status === 'FAILED'" 
                  :content="task.errorMsg" 
                  placement="top"
                >
                  <el-icon class="error-icon"><warning /></el-icon>
                </el-tooltip>
              </div>
            </div>
          </div>
          <div v-if="loading" class="loading-more">
            <el-loading style="width: 100%;" />
            <span>加载中...</span>
          </div>
          <div v-if="noMoreData" class="no-more-data">
            没有更多记录了
          </div>
        </el-scrollbar>
      </div>
    </el-card>

    <!-- 历史记录预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="历史记录预览"
      width="90%"
      class="preview-dialog"
    >
      <div class="preview-dialog-content">
        <el-image
          :src="selectedHistoryImage"
          fit="contain"
          class="preview-dialog-image"
        />
      </div>
      <template #footer>
        <div class="preview-dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="downloadImage(selectedHistoryImage)">
            下载
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import api from '../api'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'

// 历史任务相关状态
const historyTasks = ref([])
const currentPage = ref(0)
const pageSize = ref(10)
const loading = ref(false)
const noMoreData = ref(false)
const scrollbarRef = ref(null)
const taskImageUrls = ref(new Map())

// 预览对话框状态
const previewDialogVisible = ref(false)
const selectedHistoryImage = ref('')

// 格式化日期
const formatDate = (date) => {
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).format(date)
}

// 格式化字符串日期
const formatDateFromString = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return formatDate(date)
}

// 获取任务状态对应的类型
const getTaskStatusType = (status) => {
  switch (status) {
    case 'COMPLETED':
      return 'success'
    case 'FAILED':
      return 'danger'
    case 'PROCESSING':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取任务状态对应的文本
const getTaskStatusText = (status) => {
  switch (status) {
    case 'QUEUED':
      return '等待中'
    case 'PROCESSING':
      return '生成中'
    case 'COMPLETED':
      return '已完成'
    case 'FAILED':
      return '失败'
    default:
      return status
  }
}

// 获取图片并转换为blob URL
const fetchAndConvertImage = async (imageUrl) => {
  try {
    const response = await api.get(imageUrl, { responseType: 'blob' })
    return URL.createObjectURL(response)
  } catch (error) {
    console.error('获取图片失败', error)
    throw error
  }
}

// 加载历史任务
const loadHistoryTasks = async (page = 0) => {
  if (loading.value || (noMoreData.value && page > 0)) return
  
  loading.value = true
  try {
    const response = await api.get('/queue/user-tasks/history', {
      params: {
        page: page,
        size: pageSize.value
      }
    })
    
    const tasks = response.result.content || []
    
    if (page === 0) {
      historyTasks.value = tasks
    } else {
      historyTasks.value = [...historyTasks.value, ...tasks]
    }
    
    noMoreData.value = response.last || false
    currentPage.value = page
    
    await loadTaskImages(tasks)
    
  } catch (error) {
    console.error('加载历史任务失败:', error)
    ElMessage.error('加载历史记录失败')
  } finally {
    loading.value = false
  }
}

// 为任务加载图片
const loadTaskImages = async (tasks) => {
  for (const task of tasks) {
    if (task.status === 'COMPLETED' && task.imagePath && !taskImageUrls.value.has(task.taskId)) {
      try {
        const blobUrl = await fetchAndConvertImage(task.imagePath)
        if (blobUrl) {
          taskImageUrls.value.set(task.taskId, blobUrl)
        }
      } catch (error) {
        console.error(`加载任务 ${task.taskId} 的图片失败:`, error)
      }
    }
  }
}

// 处理滚动事件
const handleScroll = async (e) => {
  const { scrollTop, clientHeight, scrollHeight } = e.target
  if (scrollHeight - scrollTop - clientHeight < 100 && !loading.value && !noMoreData.value) {
    await loadHistoryTasks(currentPage.value + 1)
  }
}

// 处理历史记录项点击
const handleHistoryItemClick = (task) => {
  if (task.status === 'COMPLETED' && taskImageUrls.value.has(task.taskId)) {
    selectedHistoryImage.value = taskImageUrls.value.get(task.taskId)
    previewDialogVisible.value = true
  }
}

// 下载图像
const downloadImage = async (imageUrl) => {
  try {
    const response = await fetch(imageUrl)
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `generated-image-${Date.now()}.png`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载失败', error)
    ElMessage.error('图像下载失败')
  }
}

// 刷新历史记录
const refreshHistory = async () => {
  currentPage.value = 0
  noMoreData.value = false
  await loadHistoryTasks(0)
}

// 暴露方法给父组件
defineExpose({
  refreshHistory
})

// 组件挂载时加载历史记录
onMounted(async () => {
  await loadHistoryTasks(0)
})

// 组件卸载前清理
onBeforeUnmount(() => {
  for (const url of taskImageUrls.value.values()) {
    URL.revokeObjectURL(url)
  }
  taskImageUrls.value.clear()
})
</script>

<style scoped>
.history-panel {
  height: 100%;
  background-color: #f5f7fa;
}

.history-card {
  margin: 0;
  border-radius: 0;
  border: none;
  box-shadow: none;
  background: transparent;
  height: 100%;
}

.history-card :deep(.el-card__header) {
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.history-card :deep(.el-card__body) {
  padding: 0;
  height: calc(100% - 60px);
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.recent-generations {
  height: 100%;
}

.history-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 12px;
}

.history-item {
  background: var(--el-bg-color);
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease;
  cursor: pointer;
}

.history-item:active {
  transform: scale(0.98);
}

.history-image-container {
  position: relative;
  width: 100%;
  height: 100%;
  padding-top: 100%;
  background: var(--el-fill-color-light);
  display: flex;
  align-items: center;
  justify-content: center;
}

.history-image {
  position: absolute;
  top: 0;
  width: auto;
  height: 100%;
  object-fit: contain;
}

.image-error {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
}

.task-status {
  position: absolute;
  top: 8px;
  left: 8px;
  z-index: 1;
}

.history-info {
  padding: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.history-date {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.error-icon {
  margin-left: 4px;
  color: var(--el-color-danger);
}

.loading-more {
  padding: 16px;
  text-align: center;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.loading-more .el-loading {
  margin-bottom: 8px;
}

.no-more-data {
  padding: 16px;
  text-align: center;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

/* 预览对话框样式 */
.preview-dialog {
  margin: 0;
}

.preview-dialog :deep(.el-dialog__header) {
  margin: 0;
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.preview-dialog :deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
}

.preview-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.preview-dialog-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  background: var(--el-bg-color-page);
}

.preview-dialog-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.preview-dialog :deep(.el-dialog__footer) {
  padding: 12px 16px;
  border-top: 1px solid var(--el-border-color-light);
}

.preview-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .history-panel {
    background-color: #1a1a1a;
  }

  .history-card {
    background: transparent;
  }

  .history-item {
    background: var(--el-bg-color-overlay);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  }

  .image-error {
    background: var(--el-bg-color);
  }

  .preview-dialog-content {
    background: var(--el-bg-color);
  }
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .history-grid {
    gap: 8px;
    padding: 8px;
  }

  .history-info {
    padding: 6px;
    font-size: 11px;
  }

  .task-status {
    top: 4px;
    left: 4px;
  }

  .preview-dialog :deep(.el-dialog__header) {
    padding: 10px 12px;
  }

  .preview-dialog :deep(.el-dialog__footer) {
    padding: 10px 12px;
  }

  .preview-dialog-footer {
    gap: 6px;
  }
}
</style> 